<template>
  <v-app>
    <GoBackTopbar title="我的订单" backTo="/profile" />
    <v-content>
      <v-tabs
        background-color="white"
        color="#2AB795"
        height="40"
        slider-size="3"
        show-arrows
        next-icon="mdi-chevron-right"
        prev-icon="mdi-chevron-left"
        v-model="model"
      >
        <v-tab v-for="(item, i) in items" :key="i" :href="`#tab-${i}`">
          {{ item.tab }}
        </v-tab>
      </v-tabs>
      <v-tabs-items v-model="model">
        <v-tab-item :value="`tab-0`">
          <TabContent :orders="allOrders" />
        </v-tab-item>
        <v-tab-item :value="`tab-1`">
          <TabContent :orders="notYetPaymentOrders" />
        </v-tab-item>
        <v-tab-item :value="`tab-2`">
          <TabContent :orders="notYetReceiveOrders" />
        </v-tab-item>
        <v-tab-item :value="`tab-3`">
          <TabContent :orders="alreadyFinishedOrders" />
        </v-tab-item>
        <v-tab-item :value="`tab-4`">
          <TabContent :orders="alreadyCanceledOrders" />
        </v-tab-item>
      </v-tabs-items>
      <v-overlay :value="showOverlay">
        <v-progress-circular indeterminate size="64"></v-progress-circular>
      </v-overlay>
    </v-content>
  </v-app>
</template>

<script>
import GoBackTopbar from '@/components/GoBackTopbar.vue';
import TabContent from './components/TabContent/index.vue';
import request from '@/request';
// import pullRefresh from '@/components/pullRefresh.vue';

export default {
  name: 'my-orders',
  components: { GoBackTopbar, TabContent },
  data() {
    return {
      model: 'tab-0',
      showOverlay: false,
      orders: [],
      items: [
        { tab: '全部' },
        { tab: '待付款' },
        { tab: '待收货' },
        { tab: '已完成' },
        { tab: '已取消' }
      ],
      isRefreshing: false
    };
  },
  mounted() {
    this.$bus.on('onOrderStatusChange', this.fetchOrderData);

    this.fetchOrderData();
  },
  methods: {
    fetchOrderData() {
      this.showOverlay = true;
      const appUserId = this.$store.state.currentUser.id;
      return request.get(`/orders/list/${appUserId}`).then(resp => {
        this.orders = resp;
        this.showOverlay = false;
      });
    },
    onRefresh() {
      // 刷新前需要先手动将设为true，否则pull-refresh不会监测到状态变化
      this.isRefreshing = true;
      this.fetchOrderData().then(() => {
        this.isRefreshing = false;
      });
    }
  },
  destroyed() {
    this.$bus.off('onOrderStatusChange');
  },
  computed: {
    allOrders() {
      return this.orders;
    },
    notYetPaymentOrders() {
      return this.orders.filter(order => order.status === 0);
    },
    notYetReceiveOrders() {
      return this.orders.filter(
        order => order.status === 1 || order.status === 2
      );
    },
    alreadyFinishedOrders() {
      return this.orders.filter(order => order.status === 3);
    },
    alreadyCanceledOrders() {
      return this.orders.filter(order => order.status === 5);
    }
  }
};
</script>
